<template>
    <div>
        <el-button
            size="mini"
            type="primary"
            :loading="binNumLoading"
            class="refresh-btn"
            @click="doRefreshBin"
            icon="el-icon-refresh"
            >刷新</el-button
        >
        <el-checkbox v-model="secondChecked">全部一致</el-checkbox>
        <el-divider></el-divider>

        <div>
            格口数量：{{ binNum }}
            <el-switch v-model="binSwitch" class="binSwitch"> </el-switch>
            <i class="el-icon-question"></i>
            <span>开关打开后，点击刷新会先读取设备格口数量</span>
        </div>
        <el-form
            ref="binForm"
            :model="binForm"
            class="binForm box-detail"
            label-width="90px"
            v-loading="tab1Loading"
            element-loading-background="rgba(0, 0, 0, 0.08)"
            element-loading-text="加载中"
            element-loading-spinner="el-icon-loading"
        >
            <el-row :gutter="10" style="width: 100%">
                <el-col
                    :lg="8"
                    :xl="6"
                    v-for="(one, index) in binForm.entitys"
                    :key="index"
                >
                    <el-card style="width: 100%" class="one-card">
                        <div class="card-status">
                            <el-button
                                type="primary"
                                class="binIndex-btn"
                                :circle="true"
                                >{{ index + 1 }}</el-button
                            >
                            <div class="boxForm bin-form">
                                <!-- 0：打开 1：关闭 -->
                                <el-form-item label="仓锁状态:">
                                    <el-tag type="danger" size="mini" v-if="one['06010036'] === '0'"
                                        >打开</el-tag
                                    >
                                    <el-tag type="primary" size="mini" v-else-if="one['06010036'] === '1'"
                                        >关闭</el-tag
                                    >
                                </el-form-item>
                                <!-- 0：空仓 1：充电中 2：充满电 3：禁用 -->
                                <el-form-item label="仓状态:">
                                    <el-tag type="primary" size="mini" v-if="one['06010039'] === '0'"
                                        >空仓</el-tag
                                    >
                                    <el-tag type="danger" size="mini" v-else-if="one['06010039'] === '1'"
                                        >充电中</el-tag
                                    >
                                    <el-tag type="success" size="mini" v-else-if="one['06010039'] === '2'"
                                        >充满电</el-tag
                                    >
                                    <el-tag type="info" size="mini" v-else-if="one['06010039'] === '3'"
                                        >禁用</el-tag
                                    >
                                    <el-tag type="danger" size="mini" v-else-if="one['06010039'] === '4'"
                                        >停充</el-tag
                                    >
                                </el-form-item>
                            </div>
                        </div>

                        <div class="operate-btns">
                            <el-button
                                size="small"
                                plain type="primary"
                                :disabled="secondChecked && index > 0"
                                :loading="one[`binRefresh${index + 1}`]"
                                @click="isForbidden(2, index)"
                                >解禁
                            </el-button>
                            <el-button
                                size="small"
                                plain type="danger"
                                :disabled="secondChecked && index > 0"
                                :loading="one[`binRefresh${index + 1}`]"
                                @click="isForbidden(1, index)"
                                >禁用
                            </el-button>
                            <el-button
                                plain type="success"
                                size="small"
                                :disabled="secondChecked && index > 0"
                                :loading="one[`binSetting${index + 1}`]"
                                @click="isOpenDoor(one, index)"
                            >
                                开仓
                            </el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script>
import { handleConfirm } from "@/utils/messageBox";
import { equipment } from "@/api/factuer";

export default {
    props: {
        binVisible: {
            type: Boolean,
            default: false,
        },
        equipId: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            binNumLoading: false,
            secondChecked: false, //全部一致
            binNum: null, //格口数量
            binSwitch: false,
            binForm: {
                entitys: [],
            },
            tab1Loading: false,
            forbidList: [],
            progressList:[],
        };
    },
    watch: {
        binVisible: {
            handler(val) {
                this.resetData();
                this.readBinIndex();
            },
            immediate: true,
        },
    },
    methods: {
        resetData() {
            this.binNumLoading = false;
            this.secondChecked = false;
            this.binNum = null;
            this.binSwitch = false;
            this.tab1Loading = false;
            this.binForm = {
                entitys: [],
            };
        },
        // 读取格口数量
        readBinIndex() {
            this.binForm.entitys = [];
            equipment(
                `/operate/param/read/bincount/${this.equipId}`,
                "post",
                { refresh: this.binSwitch },
                2
            )
                .then((res) => {
                    this.binNum = res.data;
                    if (this.binNum) {
                        for (let i = 0; i < this.binNum; i++) {
                            let one = {
                                "06010036": undefined,
                                "06010039": undefined,
                            };
                            this.binForm.entitys.push(one);
                        }
                        this.doRead();
                    }
                })
                .finally(() => (this.binNumLoading = false));
        },
        doRead() {
            this.tab1Loading = true;
            let params = {
                entitys: [],
                equipId: this.equipId,
            };
            for (let i = 0; i < this.binNum; i++) {
                params.entitys.push(
                    { addrId: i + 1, id: "06010039" },
                    { addrId: i + 1, id: "06010036" }
                );
            }

            equipment("/operate/param/read", "post", params, 1)
                .then((res) => {
                    let datas = res.data;
                    datas.forEach((item) => {
                        this.binForm.entitys.forEach((pp, index) => {
                            for (const key in pp) {
                                if (
                                    item.addrId == index + 1 &&
                                    item.id == key
                                ) {
                                    pp[key] = item.value;
                                }
                            }
                        });
                    });
                })
                .finally(() => {
                    this.tab1Loading = false;
                });
        },
        doRefreshBin() {
            this.binNumLoading = this.binSwitch;
            if (this.binSwitch) {
                this.readBinIndex();
            } else {
                this.doRead();
            }
        },
        // 禁用/解禁
        isForbidden(type, index) {
            // let msg = one["06010036"] === "1" ? "解禁" : "禁用";
            // let status = one["06010036"] === "1" ? 2 : 1;
            // let type = one["06010036"];
            let msg = type == 2 ? "解禁" : "禁用";
            if (!this.secondChecked) {
                handleConfirm(
                    `确定要${msg}${index + 1}号仓吗？`,
                    "warning",
                    "提示"
                ).then((res) => {
                    this.tab1Loading = true;
                    equipment(
                        `/control/bin/control/${this.equipId}`,
                        "post",
                        {
                            addrId: index + 1,
                            value: type,
                        },
                        1
                    )
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message.success(
                                    `${index + 1}号仓${msg}成功`
                                );
                            }
                        })
                        .finally(() => (this.tab1Loading = false));
                });
            } else {
                handleConfirm(
                    `确定要${msg}${index + 1}~${this.binNum}号仓吗？`,
                    "warning",
                    "提示"
                ).then((res) => {
                    this.tab1Loading = true;
                    // 批量下发
                    this.multipleForbid(type);
                });
            }
        },
        // 开仓
        isOpenDoor(one, index) {
            if (!this.secondChecked) {
                handleConfirm(
                    `确定要打开${index + 1}号仓吗？`,
                    "warning",
                    "提示"
                ).then((res) => {
                    this.tab1Loading = true;
                    equipment(
                        `/control/bin/opendoor/${this.equipId}`,
                        "post",
                        {
                            addrId: index + 1,
                            value: 1,
                        },
                        1
                    )
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message.success(
                                    `${index + 1}号仓开仓成功`
                                );
                            }
                        })
                        .finally(() => (this.tab1Loading = false));
                });
            } else {
                handleConfirm(
                    `确定要打开${index + 1}~${this.binNum}号仓吗？`,
                    "warning",
                    "提示"
                ).then((res) => {
                    this.tab1Loading = true;
                    // 批量下发
                    this.multipleIssue();
                });
            }
        },
        // 批量下发
        multipleIssue() {
            let that = this; // 改变this指向
            
            this.$emit('showProgress');
            this.progressList = [];
            that.tab1Loading = true;

            function callPromise(index) {
                return new Promise((resolve, reject) => {
                    that.progressList.push({ index: index, result: "0" }); //开仓中

                    that.changeProgressList();
                    equipment(
                        `/control/bin/opendoor/${that.equipId}`,
                        "post",
                        {
                            addrId: index + 1,
                            value: 1,
                        },
                        1
                    )
                        .then((res) => {
                            if (res.code == 200) {
                                resolve(index);
                                that.progressList[index].result = "1"; //成功
                            } else {
                                resolve(index);
                                that.progressList[index].result = "2"; //失败
                            }
                            that.changeProgressList();
                        })
                        .catch((err) => {
                            that.progressList[index].result = "2"; //失败
                            that.tab1Loading = false;

                            that.changeProgressList();
                        });
                });
            }

            const result = this.binForm.entitys.reduce(
                (accumulatorPromise, next, index) => {
                    return accumulatorPromise.then(() => {
                        // 上一个接口执行完毕再执行下一个
                        return callPromise(index);
                    });
                },
                Promise.resolve()
            );

            result.then((e) => {
                console.log("All Promises Resolved");
                this.tab1Loading = false;
            });
        },
        changeForbidList(){
          this.$emit('changeForbidList',this.forbidList);
        },
        changeProgressList(){
          this.$emit('changeProgressList',this.progressList);
        },
        // 批量解禁/禁用
        multipleForbid(type) {
            //  type==2?'解禁':'禁用';
            let that = this; // 改变this指向
            this.$emit('showProgress');

            this.forbidList = [];
            that.tab1Loading = true;

            function callPromise(inx) {
                let index = inx;
                // status:1：禁用 2：启用 result:0进行中；1成功；2失败；3已经是当前状态，不可操作
                return new Promise((resolve, reject) => {
                    that.forbidList.push({
                        index: index,
                        result: "0",
                        status: type,
                    }); //解禁/禁用中

                    that.changeForbidList();

                    equipment(
                        `/control/bin/control/${that.equipId}`,
                        "post",
                        {
                            addrId: index + 1,
                            value: type,
                        },
                        1
                    )
                        .then((res) => {
                            if (res.code == 200) {
                                resolve(index);
                                that.forbidList[index].result = "1"; //成功
                            } else {
                                resolve(index);
                                that.forbidList[index].result = "2"; //失败
                            }
                            that.changeForbidList();
                        })
                        .catch((err) => {
                            that.forbidList[index].result = "2"; //失败
                            that.tab1Loading = false;

                            that.changeForbidList();
                        });
                });
            }

            const result = this.binForm.entitys.reduce(
                (accumulatorPromise, next, index) => {
                    return accumulatorPromise.then(() => {
                        // 上一个接口执行完毕再执行下一个
                        return callPromise(index);
                    });
                },
                Promise.resolve()
            );

            result.then((e) => {
                console.log("All Promises Resolved");
                this.tab1Loading = false;
            });
        },
    },
};
</script>
<style lang="scss" scoped>
@import "@/styles/common.scss";
// @import "./css/style.scss";
::v-deep .el-divider--horizontal {
    margin: 6px 0;
}
.binIndex-btn {
    padding: 0;
    width: 28px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    background-color: #409eff;
    border-color: #409eff;
}
.el-icon-question {
    font-size: 20px;
    margin: 0 6px 0 10px;
    color: #f56c6c;
}
.refresh-btn {
    position: absolute;
    top: 16px;
    right: 50px;
}
::v-deep .el-card__body{
  padding: 10px 0;
}
.one-card {
  margin-top: 10px;
    .card-status {
        @include flexLayout(center, space-evenly);

        .el-form-item {
            margin-bottom: 0;
        }
    }
}
.operate-btns {
    width: 100%;
    text-align: center;
    margin-top: 10px;
}
// 屏幕分辨率
@media (min-width: 1441px) {
    .binForm {
        .el-card {
            width: 32%;
        }
        .el-card:not(:nth-child(3n)) {
            margin-right: 2%;
        }
    }
}

@media (max-width: 1440px) {
    .binForm {
        .el-card {
            width: 49%;
        }
        .el-card:nth-child(2n) {
            margin-left: 2%;
        }
    }
}
</style>
